import TileLayer from "ol/layer/Tile";
import WMTS from "ol/source/WMTS"; // eslint-disable-line
import ImageWMS from 'ol/source/ImageWMS.js'
import TileArcGISRest from "ol/source/TileArcGISRest";
import VectorSource from "ol/source/Vector";
import ImageStatic from "ol/source/ImageStatic";
import VectorLayer from "ol/layer/Vector";
import ImageLayer from "ol/layer/Image";
import LayerGroup from "ol/layer/Group";
// import Cluster from "ol/source/Cluster";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { Fill, Stroke, Style,Circle as circleStyle } from "ol/style";
import {get as getProjection } from "ol/proj";
import { getTopLeft, getWidth } from "ol/extent";
import Feature from "ol/Feature";
import Polygon from "ol/geom/Polygon";
import Point from "ol/geom/Point";
// import GeoJSON from "ol/format/GeoJSON";
import Icon from "ol/style/Icon";
// import Text from "ol/style/Text";
// import Overlay from "ol/Overlay";
import { fromExtent } from "ol/geom/Polygon";
import { LinearRing, MultiPolygon } from "ol/geom";
// import { Select } from "ol/interaction";
// import { click } from "ol/events/condition";
//turf
// import * as turf from "@turf/turf";
import GeoJSON from 'ol/format/GeoJSON';

//加载WebGLPointsLayer
import Map from "ol/Map";
import View from "ol/View";
import WebGLPointsLayer from "ol/layer/WebGLPoints";
import WebGLPoints from "ol/layer/WebGLPoints";

function Layer(map) {
    this.map = map;
}
//创建webglpoints加载矢量点图层
Layer.prototype.createWebGLPointsLayer = function (
  layerName,
  zIndex,
  sourceObj,
  declutter
) {
  let _sourceObj = sourceObj == null ? { wrapX: false } : sourceObj;
  let source = new VectorSource(_sourceObj);
  // 创建 WebGLPointsLayer 实例
  let webGLPointsLayer = new WebGLPointsLayer({
    source: source,
    style: {
    
      symbol: {
        symbolType: "circle", //图标形状可选值为：circle/triangle/square/image
        size: 10,
        color: [
          "match",
          ["get", "color"],
          //降水
          "#8ff2a6",
          "#8ff2a6",
          "#ffffff",
          "#ffffff",
          "#3dba3d",
          "#3dba3d",
          "#ffb861",
          "#ffb861",
          "#ff0000",
          "#ff0000",
          "#fa00fa",
          "#fa00fa",
          "#400080",
          "#400080",
          //湿度
          "#dfffef",
          "#dfffef",
          "#800080",
          "#800080",
          "#ffff00",
          "#ffff00",
          "#ff0000",
          "#ff0000",
          "#a6ffd2",
          "#a6ffd2",
          "#3cff9d",
          "#3cff9d",
          "#ff0000",
          "#ff0000",
          //温度
          "#ffb861",
          "#ffb861",
          "#ccff66",
          "#ccff66",
          "#40ff00",
          "#40ff00",
          "#99ffff",
          "#99ffff",
          "#fdcdff",
          "#fdcdff",
          "#fdcdff",
          "#fdcdff",
          "#ff0000",
          "#ff0000",
          "#cc0000",
          "#cc0000",
          //风速
          "#fff59d",
          "#fff59d",
          "#ffee53",
          "#ffee53",
          "#ffe706",
          "#ffe706",
          "#e1cb00",
          "#e1cb00",
          "#ff6f6f",
          "#ff6f6f",
          "#ff0000",
          "#ff0000",
          //云量
          "#f7faff",
          "#f7faff",
          "#e8efff",
          "#e8efff",
          "#e8efff",
          "#e8efff",
          "#d0dfff",
          "#d0dfff",
          "#8eb3ff",
          "#8eb3ff",
          "#5189ff",
          "#5189ff",
          "#5189ff",
          "#5189ff",
          "#43ceff",
          "#43ceff",

          "#000000",
        ], //设置hover值为1时的颜色为：#ff3f3f,默认颜色为：#006688
      },
    },
    zIndex: zIndex || 15,
    declutter: declutter || false,
  });

  webGLPointsLayer.set("layerName", layerName);
  // console.log(this.map,"this.map")
  // console.log(webGLPointsLayer,"webGLPointsLayerAAAAA")
  this.map.addLayer(webGLPointsLayer);
  return webGLPointsLayer;
};
//样式函数stroke fill
let styleFunction = function(styleObj) {
  let style = {};
  if (styleObj && (styleObj.strokeColor || styleObj.strokeWidth)) {
      style.stroke = new Stroke({
          color: styleObj.strokeColor || "#FFFFFF",
          width: styleObj.strokeWidth || 1,
      });
  }
  if (styleObj && styleObj.fillColor) {
      style.fill = new Fill({
          color: styleObj.fillColor || "rgba(255,255,255,0.5)",
      });
  }
  return new Style(style);
};

/**
 * @description: 获取所有的图层
 * @return {*} 对应图层对象
 */
Layer.prototype.getAllLayers = function() {
    let layerArr = this.map.getLayers().array_;
    return layerArr;
};

/**
 * @description: 根据图层名获取图层
 * @param {string} layerName 图层名称
 * @return {*} 对应图层对象
 */
Layer.prototype.getLayerByName = function(layerName) {
    let layerArr = this.getAllLayers();
    for (let k = 0; k < layerArr.length; k++) {
        if (
            layerArr[k].values_.layerName == layerName ||
            layerArr[k].layerName == layerName
        ) {
            return layerArr[k];
        }
    }
};

/**
 * @description: 叠加WMTS
 * @param {string} layerName 图层名称
 * @param {string} url 图层路径
 * @param {object} params 参数
 * @return {TileLayer} 图层对象
 */
Layer.prototype.getTianDiTuWmtsLayerByParam = function(layerName, url, type) {
    const token = "fe40e8bfa4d16f7a68afafe70ad0483e";
    let m = parseInt(Math.random() * 8); //0-7随机选择
    const img =
        "http://t" +
        m +
        ".tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //影像底图
    const cia =
        "http://t" +
        m +
        ".tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //影像注记
    const vec =
        "http://t" +
        m +
        ".tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //影像底图
    const cva =
        "http://t" +
        m +
        ".tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //影像注记
        const ter =
        "http://t" +
        m +
        ".tianditu.gov.cn/ter_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //地形晕渲
        const cta =
        "http://t" +
        m +
        ".tianditu.gov.cn/cta_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&tk="; //地形注记
    if (!url) return null;
    url = decodeURIComponent(url);
    const projection = getProjection("EPSG:4326");
    const projectionExtent = projection.getExtent();
    const size = getWidth(projectionExtent) / 256;
    const resolutions1 = new Array(19);
    const resolutions = new Array(19);
    const matrixIds = new Array(19);
    for (let z = 0; z < 20; ++z) {
        //1.40625
        resolutions1[z] = size / Math.pow(2, z); //天地图经纬 度底图的计算参数
        resolutions[z] = 1.40625285 / Math.pow(2, z); //苍穹 底图计算参数（可能需要修改，根据点位偏移自己去调整）
        matrixIds[z] = z;
    }
    let source = new WMTS({
        name: layerName,
        url: url,
        layer: type,
        style: "default",
        matrixSet: "c",
        format: "tiles",
        wrapX: true,
        tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent), //resolutions: res.slice(0, 15),
            resolutions: resolutions,
            matrixIds: matrixIds,
        }),
    });
    source.setTileUrlFunction(function(data) {
        let tilematrix = data[0];
        let tilecol = data[1];
        let tilerow = data[2];
        let baseUrl = "";
        if (type == "img") baseUrl = img;
        if (type == "cia") baseUrl = cia;
        if (type == "vec") baseUrl = vec;
        if (type == "cva") baseUrl = cva;
        if (type == "ter") baseUrl = ter;
        if(type=="cta")baseUrl=cta;
        return (
            baseUrl +
            token +
            `&TILEMATRIX=${tilematrix}&TILECOL=${tilecol}&TILEROW=${tilerow}`
        );
    });
    let layer = new TileLayer({
        source: source,
    });
    // this.map.addLayer(layer);
    return layer;
};

/**
 * @description: 添加arcgis瓦片服务图层
 * @param {string} layerName 图层路径名称
 * @param {string} url 图层路径
 * @return {TileLayer} 图层对象
 */
Layer.prototype.getArcgisMapServer = function(layerName, url) {
    if (url) {
        const arcLayer = new TileLayer({
            source: new TileArcGISRest({
                wrapX: false,
                url: url,
            }),
        });
        if (layerName) {
            arcLayer.set("layerName", layerName);
        }
        return arcLayer;
    }
};

Layer.prototype.setWmsLayer = function (layers, layername) {
  console.log("layercheck", layers, layername);
  let imageLayer = new ImageLayer({
    zIndex: 2,
    source: new ImageWMS({
      ratio: 1,
      url: process.env.VUE_APP_BASE_API + "/geoserverA/geoserver/cite/wms",
      params: {
        //service: 'WMS',
        VERSION: '1.1.0',
        request: 'GetMap',
        LAYERS: layers,
        STYLES: '',
        FORMAT: 'image/png', //通常使用 image/png 格式   
      },
    }),
    name: `Layer${layername}`,
    opacity: 1,
  });
  imageLayer.set("layerName", `Layer${layername}`);
  this.map.addLayer(imageLayer);
};

/**
 * @description: 行政区遮罩（带洞多边形）
 * @param {*} layer 遮罩图层
 * @param {*} holeGeom 行政区多边形
 * @param {*} styleObj 遮罩样式
 * @return {*}
 */
Layer.prototype.addPolygonHoles = function(layer, holeGeom, styleObj = {}) {
    let extent = [-180, -90, 180, 90];
    let polygonRing = fromExtent(extent); //从范围创建多边形
    let coords = holeGeom.getCoordinates(); //获取此几何的坐标数组。该数组具有用于多边形的GeoJSON坐标数组的结构
    if (holeGeom instanceof MultiPolygon)
        coords.forEach((coord) => {
            let linearRing = new LinearRing(coord[0]);
            polygonRing.appendLinearRing(linearRing); //将传递的线环添加到这个多边形
        });
    else {
        let linearRing = new LinearRing(coords[0]);
        polygonRing.appendLinearRing(linearRing); //将传递的线环添加到这个多边形
    }
    let feature = new Feature({ geometry: polygonRing });
    feature.setStyle(styleFunction(styleObj));
    layer.getSource().addFeature(feature);
};

/**
 * @description: 添加一个矢量遮罩图层
 * @param {*} layerName 图层名
 * @param {*} zIndex 图层
 * @return {*} vectorLayer
 */
Layer.prototype.createMaskLayer = function(layerName, zIndex) {
    let vectorLayer = new VectorLayer({
        source: new VectorSource(),
        zIndex: zIndex || 10,
        declutter: false, //防止标注文字重复标注
        style: new Style({
            fill: new Fill({
                color: "rgba( 255, 255, 255, 0.7)",
            }),
            stroke: new Stroke({
                color: "#f4b49f",
                width: 3,
            }),
        }),
    });
    vectorLayer.set("layerName", layerName || "遮罩图层");
    this.map.addLayer(vectorLayer);
    return vectorLayer;
};

/**
 * @description: 添加json的边线图层
 * @param {*} jsonData json数据
 */
Layer.prototype.createAreaLineLayer = function(jsonData) {
  // 创建矢量数据源
  const vectorSource = new VectorSource({
    features: new GeoJSON().readFeatures(jsonData)
  });
  let data = new GeoJSON().readFeatures(jsonData);
  console.log("11111111111111",data);
  // 创建矢量图层并设置样式
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0)'//填充为空白（透明）
      }),
      stroke: new Stroke({
        color: 'blue', // 边线颜色
        width: 2
      })
    }),
    zIndex: 11
  });
  let layer = this.createGroup("边界图层组", 4, [vectorLayer]);
  this.map.addLayer(layer);
}

//创建点符号图层
Layer.prototype.createVectorLayer = function(layerName, styleObj, zIndex, sourceObj, declutter) {
  let _sourceObj = sourceObj == null ? { wrapX: false } : sourceObj
  let source = new VectorSource(_sourceObj);
  let vectorLayer = new VectorLayer({
      source: source,
      zIndex: zIndex || 15,
      declutter: declutter || false, //防止标注文字重复标注
      style: styleFunction(styleObj)
  });
  vectorLayer.set('layerName', layerName);
  this.map.addLayer(vectorLayer);
  return vectorLayer;
}

/**
 * @description: 创建一个图层组
 * @param {*} LayerGroupName 图层组名称
 * @param {*} zIndex 图层顺序
 * @param {*} layers 图层数组 []
 * @return {*} layerGroup
 */
Layer.prototype.createGroup = function(layerGroupName, zIndex, layers) {
    let layerGroup = new LayerGroup({
        layers: layers,
        zIndex: zIndex || 0,
    });
    layerGroup.set("layerName", layerGroupName || "图层组");
    return layerGroup;
};

/**
 * @description: 初始化图层，影像与矢量
 * @param {*} geom geometry对象
 */
Layer.prototype.initLayer = function(geom) {
    localStorage.setItem("xzqhGeom", JSON.stringify(geom.getCoordinates()[0]));
    //------------添加影像 全国影像 + arcgis影像
    let img = this.getTianDiTuWmtsLayerByParam("天地图影像", "img", "img");
    let cia = this.getTianDiTuWmtsLayerByParam("天地图影像注记", "cia", "cia");
    let imgLayerGroup = this.createGroup("影像图层组", 1, [img, cia]);
    

    //------------添加矢量 全国矢量 + arcgis矢量
    let vec = this.getTianDiTuWmtsLayerByParam("天地图矢量", "vec", "vec");
    let cva = this.getTianDiTuWmtsLayerByParam("天地图矢量注记", "cva", "cva");
    let vecLayerGroup = this.createGroup("矢量图层组", 2, [vec]);
    let cvaLayerGroup = this.createGroup("矢量图层组", 3, [cva]);
    cvaLayerGroup.setVisible(false);
    vecLayerGroup.setVisible(false);
    //------------添加地形
    let ter = this.getTianDiTuWmtsLayerByParam("天地图地形", "ter", "ter");
    let cta = this.getTianDiTuWmtsLayerByParam("天地图影像注记", "cta", "cta");
    let terLayerGroup = this.createGroup("地形图层组", 1, [ter, cta]);
    terLayerGroup.setVisible(false);

    this.map.addLayer(vecLayerGroup); //添加矢量
    // this.map.addLayer(imgLayerGroup); 
    this.map.addLayer(cvaLayerGroup); //添加矢量
    this.map.addLayer(terLayerGroup); //添加地形
    imgLayerGroup.setVisible(true);
    this.map.addLayer(imgLayerGroup); //添加影像

    console.log(222)

    //-------------添加地图遮罩，并将地图放大到geom范围
    // let boundaryLayer = this.createMaskLayer("行政区域遮罩图层"); //zindex为10
    // boundaryLayer.getSource().clear();
    // let extent = geom.getExtent();
    // this.fitExtentPaddingLayout(extent);
    // this.addPolygonHoles(boundaryLayer, geom, {
    //     strokeColor: "white",
    //     strokeWidth: 2,
    //     fillColor: "rgba(0,0,0,0.4)",
    // });
    //设置行政区划边界，之后用于重置地图
    // localStorage.setItem("xzqhExtent", JSON.stringify(extent));
    //返回所有图层与行政区范围
    return {
        layer: this.map.getLayers().getArray(),
        // extent: extent,
    };
};

Layer.prototype.addFeatureByGeom = function(features, zIndex, styleObj) {
    // 创建矢量图层
    let vectorLayer = new VectorLayer({
        source: new VectorSource({
            features: features
        }),
        style: styleFunction(styleObj),
        // style: ,
        zIndex: zIndex
    });
    this.map.addLayer(vectorLayer)
}


//图片图层
Layer.prototype.setImgLayer = function(url, extent, layername) {
    // let layer = this.getLayerByName("静态图片图层");
    if (url) {
        let imageLayer = new ImageLayer({
            zIndex:2,
            name: `Layer${layername}`,
            opacity: 0.6,
        });
        // 更新图片图层的源
        imageLayer.setSource(
            new ImageStatic({
                url: url,
                imageExtent: extent,
            })
        );
        imageLayer.set("layerName", "静态图片图层");
        this.map.addLayer(imageLayer);
    }
};
//消除图片图层
Layer.prototype.clearImgLayer = function(layername) {
        let layer = {}
        // console.log(layername, "clear传过来的");
        // 找到Layer图层并清除
        if (layername) {
            layer = this.map.getLayers().getArray().find(layer => layer.get('name') === `Layer${layername}`);
            // console.log(layer, "chuanle");
        }
        // 移除图层
        if (layer) {
            this.map.removeLayer(layer);
        }
    }
  
//添加Feature到图层中
Layer.prototype.addFeatureToLayer = function(layerName, polygons, style) {
    let layer = this.getLayerByName(layerName);
    if (layer) {
        let features = [];
        polygons.forEach((item, index) => {
            if (item) {
                let feature = new Feature({
                    geometry: new Polygon([item]),
                });
                // 创建样式函数
                // 创建样式函数
                let styleFunc = function() {
                    return new Style({
                        fill: new Fill({
                            color: style.fill,
                        }),
                    });
                };
                // 设置要素的样式
                feature.setStyle(styleFunc);
                feature.type = "预警区裁剪";
                feature.index = index;
                features.push(feature);
            }
        });
        // 将要素添加到矢量图层
        layer.getSource().addFeatures(features);
        return features
    } else {
        return null
    }
}

//添加预警区
Layer.prototype.addGridArea = function (polygons) {
    console.log(polygons, "polygons");
    let features = [];
    polygons.forEach((item, index) => {
      if (item) {
        let points = item.points;
        let feature = new Feature({
          geometry: new Polygon([points]),
          //标注信息
          // markerInfo: markerInfo||''
        });
        // 创建样式函数
        let styleFunc = function () {
          if (item.level == "0") {
            return new Style({
              fill: new Fill({
                color: "yellow",
              }),
            });
          } else if (item.level == "1") {
            return new Style({
              fill: new Fill({
                color: "orange",
              }),
            });
          }
          else if (item.level == "2") {
            return new Style({
              fill: new Fill({
                color: "red",
              }),
            });
          } else {
            return new Style({
              fill: new Fill({
                color: "#ffff0000",
              }),
            });
          }
        };
        // 设置要素的样式
        feature.setStyle(styleFunc);
        feature.setProperties(item);
        feature.type = "预警区";
        feature.index = index;
        features.push(feature);
      }
    });
    let layer = this.getLayerByName("预警区图层");
    //先清空图层
    layer.getSource().clear();
    // 将要素添加到矢量图层
    layer.getSource().addFeatures(features);
    let extent = layer.getSource().getExtent();
    extent[0] != Infinity &&
      this.fitExtentPadding(extent, [150, 150, 150, 100], 1000);
  }

  /**
 * @description: 添加隐患点
 * @param {*} geom geometry对象
 */
Layer.prototype.addYhdPoint = function (pointsdata,countData) {
    let features = [];
    let countDataFeatures = [];
    // let colorfeaturesR = [];
    // let colorfeaturesO = [];
    // let colorfeaturesY = [];
    // let colorfeaturesB = [];
    //隐患点
    console.log(pointsdata,"pointsdata");
    pointsdata.forEach((points) => {
      points.data.forEach((item, index) => {
        if (item?.lon && item?.lat) {
          // 创建点几何体
          let point = new Point([Number(item.lon), Number(item.lat)]); // x和y分别是点的经度和纬度
          // 创建点要素
          let feature = new Feature(point);
          // 创建样式函数
          let styleFunc = function () {
            return new Style({
              image: new Icon({
                // src: require("@/assets/images/fxgl/zhd/" + item.zhdtype + ".png"),
                scale: 0.7,
              }),
            });
          };
  
          // 设置要素的样式
          feature.setStyle(styleFunc);
          feature.setProperties(item);
          feature.type = points.yhdtype;
          feature.index = index;
          features.push(feature);
        }
      });
    })
   //区县隐患点统计
   countData.forEach((points)=>{
      // 创建点几何体
      let point = new Point([Number(points.lon), Number(points.lat)]); // x和y分别是点的经度和纬度
      // 创建点要素
      let feature = new Feature(point);
       // 设置样式函数
       let styleFunc = function () {
        return new Style({
          image: new Icon({
            // src: require("@/assets/images/fxgl/zhd/markerCount.png"),
            scale: 0.6,
          }),
          text: new Text({
            font: "bold 20px sans-serif",
            text: points.adname + "\n" + points.value ,
            fill: new Fill({
              color: "#fff",
            }),
            offsetY: -5, // 偏移量，使文本位于点的上方
          }),
        });
      };
  
      // 设置要素的样式
      feature.setStyle(styleFunc);
      countDataFeatures.push(feature);
  
   })
    // const source = new VectorSource({
    //   features,
    // });
    // const clusterSource = new Cluster({
    //   distance: 200, // 聚合点与点之间的距离
    //   // minDistance: 200, // 聚合点与点之间的最小距离
    //   source: source,
    // });
    const countDataSource = new VectorSource({
      features: countDataFeatures,
    });
    const style = function (feature) {
      // 点的个数
      const size = feature.get("features").length;
      // console.log(feature, "style");
      return new Style({
        image: new circleStyle({
          // 圆形
          radius: 20, // 半径
          stroke: new Stroke({
            // 边框
            color: "#fff",
          }),
          fill: new Fill({
            // 填充
            color: "#3399CC",
          }),
        }),
        text: new Text({
          // 文字样式
          font: "15px sans-serif",
          text: size.toString(),
          fill: new Fill({
            color: "#fff",
          }),
        }),
      });
    };
  
    let layer = this.getLayerByName("隐患点图层");
    // 先清空图层
    layer.getSource().clear();
    // layer.setSource(countDataSource);
    // layer.setSource(colorsource);
    layer.setStyle(style);
    // 将要素添加到矢量图层
    let extent = layer.getSource().getExtent();
    console.log(extent[0], "extent");
    let defaultExtent = JSON.parse(localStorage.getItem("xzqhExtent"))
    extent[0] != Infinity ?
      this.fitExtentPadding(extent, [150, 150, 150, 100], 1000) : this.fitExtentPadding(defaultExtent, [150, 150, 50, 50], 1000);
    this.map.on("moveend", () => {
      const zoom = this.map.getView().getZoom(); //获取当前地图的缩放级别
      if (zoom >= 11) {
        layer.setSource(new VectorSource());
        layer.getSource().addFeatures(features);
      } else if(zoom>=7 && zoom<11){
        layer.setSource(countDataSource);
      }else{
        layer.setSource(new VectorSource());
      }
    });
  };
//添加面雨量多边形
Layer.prototype.addMylPolygon = function (polygons) {
  let features = [];
  let extents = [];
  polygons.forEach((item, index) => {
    if (item) {
      let points = item.basinPerimeterArray;
      let feature = new Feature({
        geometry: new Polygon(points),
        //标注信息
        // markerInfo: markerInfo||''
      });
      // 创建样式函数
      let styleFunc = function (feature) {
        return new Style({
          fill: new Fill({
            color: "pink",
          }),
        });
      };
      // 设置要素的样式
      feature.setStyle(styleFunc);
      feature.setProperties(item);
      feature.type = "面雨量";
      feature.index = index;
      features.push(feature);
      extents.push(feature.getGeometry().getExtent());
    }
  });
  let layer = this.getLayerByName("雨量图层");
  //先清空图层
  layer.getSource().clear();
  // 将要素添加到矢量图层
  layer.getSource().addFeatures(features);

 
};
/**
 * @description: 地图放大到某个区域
 * @param {*} extent 范围
 * @param {*} paddingList 边距
 * @return {*}
 */
Layer.prototype.fitExtentPadding = function(extent, paddingList, duration) {
    this.map.getView().fit(extent, {
        duration: duration || 0, // 动画持续时间（毫秒）
        padding: paddingList || [0, 0, 0, 0], // 可根据需要调整填充值
    });
};

//[100, 0, 20, 0]相对于布局的padding
Layer.prototype.fitExtentPaddingLayout = function(extent, duration) {
    this.fitExtentPadding(extent, [100, 0, 20, 0], duration);
};

Layer.prototype.fitFeature = function(feature, duration) {
    this.map.getView().fit(feature.getGeometry().getExtent(), {
        duration: duration || 0, // 动画持续时间（毫秒）
    });
};

Layer.prototype.fitSource = function(vectorSource, duration) {
    this.map.getView().fit(vectorSource.getExtent(), {
        duration: duration || 0, // 动画持续时间（毫秒）
    });
};

Layer.prototype.fitExtent = function(extent, duration) {
    console.log("extent");
    this.map.getView().fit(extent, {
        duration: duration || 0, // 动画持续时间（毫秒）
    });
};


export default Layer;